//
//  NewFeatureCVC.swift
//  我的微博
//
//  Created by shmily on 15/7/30.
//  Copyright © 2015年 Stanford-IOS8-Swift-shmilyAshen. All rights reserved.
//

import UIKit

private let reuseIdentifier = "newFeatureCell"

class NewFeatureCVC: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    //设置布局
    init() {
        super.init(collectionViewLayout: Layout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private let pageNumber = 4
    
    // MARK: UICollectionView数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pageNumber
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
    
        cell.nowPage = indexPath.item
        // Configure the cell
    
        return cell
    }
    
    //翻转结束之后才开启动画
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        let path = collectionView.indexPathsForVisibleItems().last!
        
        //如果是最后一个页面,显示动画
        if path.item == (pageNumber - 1) {
             let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
             cell.startAnimation()
        }
    }

}

//新特性的 cell
class NewFeatureCell : UICollectionViewCell {
    
    //当前页面
    var nowPage: Int = 0{
        didSet{
        imgView.image = UIImage(named: "new_feature_\(nowPage + 1)")
        }
    }
    
    ///按钮点击事件
    func btnStartExperience() {
        //发送通知,设置根控制器为主界面
        NSNotificationCenter.defaultCenter().postNotificationName(switchVCNotification, object: true)
    }

    //MARK:- 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubviews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:- 添加子控件
    private func addSubviews() {
        addSubview(imgView)
        addSubview(btnStartFeel)
        
        //布局控件
        imgView.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":imgView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":imgView]))
        //布局按钮
        btnStartFeel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: btnStartFeel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: btnStartFeel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
        
    }
    
    ///开启动画
    private func startAnimation() {
        btnStartFeel.hidden = false
        btnStartFeel.userInteractionEnabled = false
        btnStartFeel.transform = CGAffineTransformMakeScale(0, 0)
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
        
                self.btnStartFeel.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                self.btnStartFeel.userInteractionEnabled = true
        }
    }
    
    //MARK: - 懒加载控件
    //imgView 背景图片
    private lazy var imgView = UIImageView()
    //立即体验
    private lazy var btnStartFeel:UIButton = {
        let btn = UIButton()
        btn.hidden = true
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setTitle("立即体验", forState: UIControlState.Normal)
        btn.addTarget(self, action: "btnStartExperience", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
}

//设置布局
class Layout : UICollectionViewFlowLayout {
    
    override func prepareLayout() {
        itemSize = UIScreen.mainScreen().bounds.size
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}

